package com.example.husbandry_online.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.husbandry_online.Constants.UserConstants;
import com.example.husbandry_online.MainActivity;
import com.example.husbandry_online.R;
import com.example.husbandry_online.Util.RandomCode;
import com.example.husbandry_online.model.User;
import com.example.husbandry_online.retrofit.ResponseModel;
import com.example.husbandry_online.retrofit.ServiceGetter;
import com.example.husbandry_online.service.UserService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RegisterPhoneFragment extends Fragment {
    View root;

    //验证码登录or忘记密码
    TextView phoneOrforget;
    //登录or验证
    Button loginOrverification;
    //发送验证码
    Button sendCode;
    //得到两个EditText
    EditText firstEdit;
    EditText secondEdit;

    String telephone;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(root == null) {
            root = inflater.inflate(R.layout.fragment_register_phone, container, false);
        }
        return root;
    }
    //注册 登录 的点击事件（验证码登录页面）
    public void loginButtonOnclick(){
        loginOrverification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                telephone = firstEdit.getText().toString();
                //Log.v("ljh","登录");
                if (telephone.equals("")){
                    Toast.makeText(getContext(),"手机号不能为空",Toast.LENGTH_LONG);
                }else {
                    if (secondEdit.getText().toString().equals(UserConstants.USER_SENDED_CODE)){
                        Toast.makeText(getContext(),"验证码输入正确",Toast.LENGTH_LONG).show();
                        //验证码输入正确，进行页面切换
                        Intent intent = new Intent(getContext(), MainActivity.class);
                        startActivity(intent);
                    }else {
                        //验证码输入有误
                        Toast.makeText(getContext(),"验证码输入有误",Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }
    //注册 完成 的点击事件（忘记密码页面）
    public void setButtonOnclick(){
        loginOrverification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String firstEditString = firstEdit.getText().toString();
                String secondEditString = secondEdit.getText().toString();
                if (firstEditString.equals("") || secondEditString.equals("")) {
                    Toast.makeText(getContext(), "输入内容不能为空", Toast.LENGTH_LONG).show();
                } else if (firstEditString.equals(secondEditString)) {
                    UserService userService = ServiceGetter.getService(UserService.class);
                    userService.forgetAndChangePwd(telephone,firstEditString).enqueue(new Callback<ResponseModel<String>>() {
                        @Override
                        public void onResponse(Call<ResponseModel<String>> call, Response<ResponseModel<String>> response) {
                            ResponseModel<String> body = response.body();
                            if (body.getResult().equals("SUCCESS")){
                                Toast.makeText(getContext(), "更改成功", Toast.LENGTH_LONG).show();
                                changeRegisterFrag(new LoginFragment());
                            }else {
                                Toast.makeText(getContext(), "更改失败："+body.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseModel<String>> call, Throwable t) {
                            Toast.makeText(getContext(),"网络繁忙，请重新尝试",Toast.LENGTH_LONG).show();

                            t.printStackTrace();
                        }
                    });
                } else {
                    Toast.makeText(getContext(), "两次密码不一致，请重新输入", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    //注册 验证 的点击事件（忘记密码页面）
    public void verificationButtonOnclick(){
        //注册”验证“点击事件
        loginOrverification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                telephone = firstEdit.getText().toString();
                if (telephone.equals("")){
                    Toast.makeText(getContext(),"手机号不能为空，请输入手机号码",Toast.LENGTH_LONG).show();
                }else {
                    String codeByUser = secondEdit.getText().toString();
                    if (codeByUser.equals(UserConstants.USER_SENDED_CODE)) {
                        //设置输入框为密码类型
                        firstEdit.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        secondEdit.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        Log.v("ljh", "验证");
                        phoneOrforget.setText("设置新密码");
                        loginOrverification.setText("完成");
                        sendCode.setVisibility(View.INVISIBLE);

                        firstEdit.setText("");
                        secondEdit.setText("");
                        firstEdit.setHint("请输入新密码");
                        secondEdit.setHint("请确认新密码");

                        firstEdit.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        secondEdit.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

                        setButtonOnclick();
                    } else {
                        Toast.makeText(getContext(), "验证码不正确，请重新输入", Toast.LENGTH_LONG).show();
                    }

                }
            }
        });
    }
    //注册 发送验证码 点击事件
    public void sendCodeButtonOnclick(){
        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹窗，进行人机验证
                isPersonOrComputer();
            }
        });
    }

    public void init(){
        //上面标题的TextView获取
        phoneOrforget = getActivity().findViewById(R.id.phoneOrforget);
        //下面是登录还是验证的按钮的获取
        loginOrverification = getActivity().findViewById(R.id.loginOrverification);
        //发送验证码按钮的获取
        sendCode = getActivity().findViewById(R.id.sendCodeInPhoneLogin);
        firstEdit = getActivity().findViewById(R.id.PhoneRegisterFirstEdit);
        secondEdit = getActivity().findViewById(R.id.PhoneRegisterSecondEdit);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        init();

        //根据phoneorforget的值来确定是 忘记密码页面 还是 验证码登录页面
        Bundle bundle = getArguments();
        int phoneorforget = bundle.getInt("show");

        //注册 发送验证码 点击事件
        sendCodeButtonOnclick();

        if (phoneorforget == 1){
            //手机验证码登录页面

            //注册"登录“点击事件
            loginButtonOnclick();
        }else {
            phoneOrforget.setText("忘记密码");
            loginOrverification.setText("验证");

            //注册 验证 的点击事件
            verificationButtonOnclick();
        }
    }

    public void changeRegisterFrag(Fragment newFragment){
        //Log.v("ljh","sadsadsadas");
        LoginAndRegisterActivity activity = (LoginAndRegisterActivity) getActivity();
        activity.changeFragment(newFragment);
    }

    public void isPersonOrComputer(){
        RandomCode.createAlertAndCode(getContext(),getActivity(),firstEdit.getText().toString(),getResources().getColor(R.color.red),UserConstants.CURRENT_PAGE_IS_LOGINBYPHONECODE);
    }

}